import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/home/Home.vue'
import Layout from '../views/layout/Index.vue'
// import Login from '../views/login/Login.vue'
import Login from '../views/login/Login2.vue'
import { useAuthStore } from '../stores/auth'
// 产品列表，懒加载模式
const Product = () => import('../views/product/Product.vue')
const ProductList = () => import('../views/product/list/List.vue')
const Category = () => import('../views/product/category/Category.vue')
const AddProduct = () => import('../views/product/addProduct/AddProduct.vue')

// 订单列表，懒加载模式
const Order = () => import('../views/order/Index.vue')
const OrderList = () => import('../views/order/list/List.vue')
const OrderSummary = () => import('../views/order/summary/Summary.vue')


const routes = [
  {
    path: '/',
    name: 'layout',
    component: Layout,
    children: [
      {
        path: '/',
        name: 'home',
        component: HomeView,
        meta: { requiresAuth: true }
      },
      {
        path: '/product',
        name: 'product',
        component: Product,
        children: [
          {
            path: 'list',
            name: 'productList',
            component: ProductList
          },
          {
            path: 'category',
            name: 'category',
            component: Category
          },
          {
            path: 'addproduct',
            name: 'addproduct',
            component: AddProduct,
            meta: { 
              activeMenu: "/product/list" 
            }
          }
        ]
      },
      {
        path: '/order',
        name: 'order',
        component: Order,
        children: [
          {
            path: 'list',
            name: 'orderList',
            component: OrderList
          },
          {
            path: 'summary',
            name: 'summary',
            component: OrderSummary
          }
        ]
      },
    ]
  },
  {
    path: '/login',
    name: 'login',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: Login
  }
]

const router = createRouter({
  // mode: "hash",
  history: createWebHistory(process.env.BASE_URL),
  routes
})

router.beforeEach((to, from, next) => {
  const authStore = useAuthStore();
  
  if (to.meta.requiresAuth && !authStore.isLoggedIn) {
    // 用户未登录且尝试访问受保护的页面，则重定向到登录页
    next({ path: '/login' });
  } else {
    // 用户已登录或访问的是无需权限验证的页面，则允许访问
    next();
  }
});

export default router
